package org.dreamwork.jasmine2.web.controls;

import org.apache.log4j.Logger;
import org.dreamwork.jasmine2.configure.JasmineConfig;
import org.dreamwork.jasmine2.engine.HttpContext;
import org.dreamwork.jasmine2.events.EventException;
import org.dreamwork.jasmine2.i18n.I18nUtil;
import org.dreamwork.jasmine2.util.StringConverter;
import org.dreamwork.jasmine2.web.IWebControl;
import org.dreamwork.util.StringUtil;

import javax.servlet.ServletContext;
import java.io.PrintWriter;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: seth
 * Date: 2009-2-5
 * Time: 13:57:07
 */
public abstract class DynamicControl extends WebControl {
    private Object content;
    protected abstract Object buildContent () throws Throwable;

    private static final Logger logger = Logger.getLogger (DynamicControl.class);

    protected DynamicControl () {
        id = "DynamicControl_" + StringConverter.generateUUID ();
    }

    public void onDataBind (Object sender) throws EventException {
        try {
            content = buildContent ();
        } catch (Throwable t) {
            logger.fatal (t.getMessage (), t);
            throw new EventException (t);
        }
    }

    @Override
    public void onPrerender (IWebControl sender, HttpContext context) throws EventException {
        if (!(content instanceof CharSequence)) return;

        String result = content.toString ();
        if (!StringUtil.isEmpty (result)) {
            ServletContext application = context.getApplication ();
            if (application.getAttribute (JasmineConfig.JASMINE_I18N_HOLDER) != null) {
                result = I18nUtil.eval (result, this);
            }
            content = I18nUtil.escapeI18n (result);
        }

    }

    public void render (PrintWriter writer) throws IOException, EventException {
        if (content == null) return;
        writer.print (content);
    }
}